﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;

namespace BLL.Dal
{

    /// <summary>
    /// 数据访问类:tbDictionary
    /// </summary>
    public partial class SysDictionaryDAL
    {
        public SysDictionaryDAL()
        { }
        #region  BasicMethod

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(Guid ID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from tbDictionary");
            strSql.Append(" where ID=@ID ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@ID", OleDbType.Guid)			};
            parameters[0].Value = ID;

            return DbHelperOleDb.Exists(strSql.ToString(), parameters);
        }


        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool Add(Model.SysDictionary model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into tbDictionary(");
            strSql.Append("ID,dicName,dicKey,parentKey,indexNum,isActive)");
            strSql.Append(" values (");
            strSql.Append("@ID,@dicName,@dicKey,@parentKey,@indexNum,@isActive)");
            OleDbParameter[] parameters = {
					new OleDbParameter("@ID", OleDbType.Guid),
					new OleDbParameter("@dicName", OleDbType.VarChar,255),
					new OleDbParameter("@dicKey", OleDbType.VarChar,255),
					new OleDbParameter("@parentKey", OleDbType.VarChar,255),
					new OleDbParameter("@indexNum", OleDbType.Integer,4),
					new OleDbParameter("@isActive", OleDbType.Boolean,1)};
            parameters[0].Value = Guid.NewGuid();
            parameters[1].Value = model.dicName;
            parameters[2].Value = model.dicKey;
            parameters[3].Value = model.parentKey;
            int indexNum = GetIndexNum(model.parentKey) + 1;
            parameters[4].Value = indexNum;
            parameters[5].Value = model.isActive;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取当前父节点的所有孩子数
        /// </summary>
        /// <param name="parentCode">父级节点标识</param>
        /// <returns></returns>
        public int GetIndexNum(string parentCode)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(*) from tbDictionary ");
            strSql.Append(" where parentKey=@parentKey ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@parentKey", OleDbType.VarChar,255)};

            parameters[0].Value = parentCode;

            object obj = DbHelperOleDb.GetSingle(strSql.ToString(), parameters);

            if (obj != null)
            {
                return (int)obj;
            }
            return 0;
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Model.SysDictionary model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update tbDictionary set ");
            strSql.Append("dicName=@dicName,");
            strSql.Append("dicKey=@dicKey,");
            strSql.Append("parentKey=@parentKey,");
            strSql.Append("indexNum=@indexNum,");
            strSql.Append("isActive=@isActive");
            strSql.Append(" where ID=@ID ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@dicName", OleDbType.VarChar,255),
					new OleDbParameter("@dicKey", OleDbType.VarChar,255),
					new OleDbParameter("@parentKey", OleDbType.VarChar,255),
					new OleDbParameter("@indexNum", OleDbType.Integer,4),
					new OleDbParameter("@isActive", OleDbType.Boolean,1),
					new OleDbParameter("@ID", OleDbType.Guid)};
            parameters[0].Value = model.dicName;
            parameters[1].Value = model.dicKey;
            parameters[2].Value = model.parentKey;
            parameters[3].Value = model.indexNum;
            parameters[4].Value = model.isActive;
            parameters[5].Value = model.ID;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(Guid ID)
        {
            Model.SysDictionary dicModel = GetModel(ID);
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from tbDictionary ");
            strSql.Append(" where ID=@ID ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@ID", OleDbType.Guid)			};
            parameters[0].Value = ID;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                UpdateIndexNum(dicModel.parentKey, dicModel.indexNum);
                DelAllChild(dicModel.dicKey);
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 更新行号
        /// </summary>
        public void UpdateIndexNum(string nodeParentCode, int? nodeIndexNum)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update  tbDictionary set indexNum=indexNum-1  ");
            strSql.Append(" where parentKey=@parentKey and indexNum>=@indexNum");
            OleDbParameter[] parameters = {
					new OleDbParameter("@parentKey", OleDbType.VarChar,255),	
                    new OleDbParameter("@indexNum", OleDbType.Integer)	};
            parameters[0].Value = nodeParentCode;
            parameters[1].Value = nodeIndexNum;

            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString(), parameters);

        }

        /// <summary>
        /// 删除所有子级节点
        /// </summary>
        /// <param name="strParentCode">父节点标识</param>
        public void DelAllChild(string strParentCode)
        {
            string strSql = "select * from tbDictionary where parentKey=@parentKey";
            OleDbParameter[] parameters = {
					new OleDbParameter("@parentKey", OleDbType.VarChar,255)			};
            parameters[0].Value = strParentCode;

            DataTable dtAllChild = DbHelperOleDb.Query(strSql, parameters).Tables[0];

            for (int i = 0; i < dtAllChild.Rows.Count; i++)
            {
                StringBuilder strSqlTemp = new StringBuilder();
                strSqlTemp.Append("delete from tbDictionary ");
                strSqlTemp.Append(" where dicKey=@dicKey ");
                OleDbParameter[] parametersTemp = {
					new OleDbParameter("@dicKey", OleDbType.VarChar,255)			};
                parameters[0].Value = dtAllChild.Rows[i]["dicKey"].ToString();

                int rows = DbHelperOleDb.ExecuteSql(strSqlTemp.ToString(), parameters);

                DelAllChild(dtAllChild.Rows[i]["dicKey"].ToString());
            }
        }

        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string IDlist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from tbDictionary ");
            strSql.Append(" where ID in (" + IDlist + ")  ");
            int rows = DbHelperOleDb.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.SysDictionary GetModel(Guid ID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ID,dicName,dicKey,parentKey,indexNum,isActive from tbDictionary ");
            strSql.Append(" where ID=@ID ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@ID", OleDbType.Guid)			};
            parameters[0].Value = ID;

            Model.SysDictionary model = new Model.SysDictionary();
            DataSet ds = DbHelperOleDb.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.SysDictionary DataRowToModel(DataRow row)
        {
            Model.SysDictionary model = new Model.SysDictionary();
            if (row != null)
            {
                if (row["ID"] != null && row["ID"].ToString() != "")
                {
                    model.ID = new Guid(row["ID"].ToString());
                }
                if (row["dicName"] != null)
                {
                    model.dicName = row["dicName"].ToString();
                }
                if (row["dicKey"] != null)
                {
                    model.dicKey = row["dicKey"].ToString();
                }
                if (row["parentKey"] != null)
                {
                    model.parentKey = row["parentKey"].ToString();
                }
                if (row["indexNum"] != null && row["indexNum"].ToString() != "")
                {
                    model.indexNum = int.Parse(row["indexNum"].ToString());
                }
                if (row["isActive"] != null && row["isActive"].ToString() != "")
                {
                    if ((row["isActive"].ToString() == "1") || (row["isActive"].ToString().ToLower() == "true"))
                    {
                        model.isActive = true;
                    }
                    else
                    {
                        model.isActive = false;
                    }
                }
            }
            return model;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ID,dicName,dicKey,parentKey,indexNum,isActive ");
            strSql.Append(" FROM tbDictionary ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            return DbHelperOleDb.Query(strSql.ToString());
        }

        /// <summary>
        /// 根据父节点获得数据列表
        /// </summary>
        public DataSet GetListByParCode(string parKey)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from  tbDictionary ");
            strSql.Append(" where  parentKey=@parentKey ");
            OleDbParameter[] parameters = {
					new OleDbParameter("@parentKey", OleDbType.VarChar)			};
            parameters[0].Value = parKey;
            return DbHelperOleDb.Query(strSql.ToString(), parameters); ;
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetRecordCount(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM tbDictionary ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            object obj = DbHelperOleDb.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {

            int pageSize = endIndex - startIndex;
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from ( ");


            strSql.Append(" select top ");
            ///页大小
            strSql.Append(pageSize);
            strSql.Append(" * from ( ");

            #region
            strSql.Append(" select top ");
            strSql.Append(endIndex);
            strSql.Append(" * from tbDictionary ");
            strSql.Append("where " + strWhere);
            strSql.Append("order by indexNum asc");
            #endregion

            strSql.Append(")");
            strSql.Append(" order by indexNum desc");

            strSql.Append(")");
            strSql.Append(" order by indexNum asc");

            return DbHelperOleDb.Query(strSql.ToString());

        }

        /// <summary>
        /// 根据上级标识取得字典定义表
        /// </summary>
        /// <param name="strCode">上级标识</param>
        /// <returns></returns>
        public Dictionary<string, string> GetDicFromParentCode(string strCode)
        {
            Dictionary<string, string> dicReturn = new Dictionary<string, string>();

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select dicKey,dicName ");
            strSql.Append(" FROM tbDictionary ");
            strSql.Append(" where parentKey='" + strCode + "'");

            DataTable dtReturn = DbHelperOleDb.Query(strSql.ToString()).Tables[0];

            if (dtReturn.Rows.Count > 0)
            {
                for (int i = 0; i < dtReturn.Rows.Count; i++)
                {
                    dicReturn.Add(dtReturn.Rows[i]["dicKey"].ToString(), dtReturn.Rows[i]["dicName"].ToString());
                }
            }

            return dicReturn;
        }

        /*
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetList(int PageSize,int PageIndex,string strWhere)
        {
            OleDbParameter[] parameters = {
                    new OleDbParameter("@tblName", OleDbType.VarChar, 255),
                    new OleDbParameter("@fldName", OleDbType.VarChar, 255),
                    new OleDbParameter("@PageSize", OleDbType.Integer),
                    new OleDbParameter("@PageIndex", OleDbType.Integer),
                    new OleDbParameter("@IsReCount", OleDbType.Boolean),
                    new OleDbParameter("@OrderType", OleDbType.Boolean),
                    new OleDbParameter("@strWhere", OleDbType.VarChar,1000),
                    };
            parameters[0].Value = "tbDictionary";
            parameters[1].Value = "ID";
            parameters[2].Value = PageSize;
            parameters[3].Value = PageIndex;
            parameters[4].Value = 0;
            parameters[5].Value = 0;
            parameters[6].Value = strWhere;	
            return DbHelperOleDb.RunProcedure("UP_GetRecordByPage",parameters,"ds");
        }*/

        #endregion  BasicMethod
        #region  ExtensionMethod

        #endregion  ExtensionMethod
    }
}
